package com.demo.webapp.kcfinder.result;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import com.demo.webapp.kcfinder.config.ResultConfig;
import com.demo.webapp.kcfinder.context.ActionContext;

public class ActionJsonResult implements Result {

	@Override
	public String render(ActionContext context, ResultConfig config) throws IOException {
		
		String encoding = context.getEncoding();
		Map<String, Object> result = context.getResult();
		//HttpServletRequest request = context.getRequest();
		HttpServletResponse response = context.getResponse();
		
		PrintWriter out = null;
		try {
			//设置是JSON数据
			preRender(response, encoding, "application/json; charset=" + encoding);
			out = response.getWriter();
			
			map2Json(result, out);
			
			out.flush();
			out.close();
		} catch (IOException e) {
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
		}
		return null;
	}

	private void preRender(HttpServletResponse response, String encoding, String contentType) {
		response.setCharacterEncoding(encoding);
    	response.setHeader("Content-Language", encoding);
    	response.setContentType(contentType);
    	response.setHeader("Pragma", "no-cache");
    	response.setHeader("cache-control", "no-cache");
    	response.setHeader("Expires", "Thu, 01 Jan 1970 00:00:00 GMT");
	}
	
	protected void map2Json(Map<String, Object> result, Writer out) throws IOException {
		ObjectMapper mapper = new ObjectMapper();
		
		try {
			mapper.writeValue(out, result);
		} catch (JsonGenerationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}
}
